const Service = require('../../../../core/service/ApiService');

class UserService extends Service{
    //用户注册
    async register(phone,pwd) {
        const dao = this.service.china.pc.user.dao;
        const InfoFromDb = await dao.getInfoFromDb(phone);
        if(InfoFromDb)
            throw new this.error.BusinessError('该账号已经注册，请直接登录');
        const newpwd = this.helper.sha1(pwd);
        await dao.register(phone,newpwd);
    }

    //登录
    async login(info) {
        const dao = this.service.china.pc.user.dao;
        const UserInfo = await dao.getInfoFromDb(info.phone);
        if(!UserInfo)
            throw new this.error.BusinessError('不存在该账户');
        const newPwd = this.helper.sha1(info.pwd);
        if(newPwd!==UserInfo.pwd)
            throw new this.error.BusinessError('密码错误');
        this.ctx.session.phone = UserInfo.phone;
        if(info.remember)
            this.ctx.session.maxAge = 604800000;  //7天
        return {
            id:UserInfo.id,
            phone:UserInfo.phone,
            nick_name:UserInfo.nick_name
        }
    }

    //退出登录
    async logout(){
        this.ctx.session=null;
    }

}

module.exports = UserService;
